package cn.com.dcsgo.springcloudstudy.payment.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author Dcsgo
 * @since 2024-08-06
 */
@Slf4j
@Service
public class PaymentService {
    /**
     * 正常访问测试
     *
     * @param id id
     * @return String
     */
    public String paymentInfo_Ok(Integer id) {
        return "线程池：" + Thread.currentThread().getName() + "paymentInfo(" + id + ")";
    }

    /**
     * 超时访问
     *
     * @param id id
     * @return String
     */
    @HystrixCommand(fallbackMethod = "paymentInfoTimeoutHelper", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public String paymentInfo_Timeout(Integer id) {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            log.info("paymentInfo_Timeout", e);
        }
        return "线程池：" + Thread.currentThread().getName()
                + "paymentInfo(" + id + ")" + "耗时2s";
    }

    /**
     * 超时访问的降级方法(要与预料会超时访问的方法的参数相匹配)
     *
     * @return string
     */
    public String paymentInfoTimeoutHelper(Integer id) {
        return "线程池：" + Thread.currentThread().getName() + " 系统繁忙，请稍后再试 " + id;
    }

    /**
     * 运行异常的服务降级示例方法
     *
     * @param id 示例参数
     * @return String
     */
    @HystrixCommand(fallbackMethod = "paymentInfoTimeoutHelper", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public String paymentInfoRunWithError(Integer id) {
        //异常导致错误
        int age = 10 / 0;
        return "就不可能走到这儿";
    }

    @HystrixCommand(fallbackMethod = "paymentCircuitBreakerFallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),//时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")//失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException("id 不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + serialNumber;
    }

    public String paymentCircuitBreakerFallback(Integer id) {
        return "id 不能为负数，请稍后再试 " + id;
    }
}
